package com.dongdongshop.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import com.dongdongshop.constant.RedisConstant;
import com.dongdongshop.mapper.TbOrderItemMapper;
import com.dongdongshop.mapper.TbOrderMapper;
import com.dongdongshop.pojo.TbOrder;
import com.dongdongshop.pojo.TbOrderExample;
import com.dongdongshop.pojo.TbOrderItem;
import com.dongdongshop.pojo.TbUser;
import com.dongdongshop.service.OrderItemService;
import com.dongdongshop.service.OrderService;
import com.dongdongshop.util.IdWorker;
import com.dongdongshop.util.RedisUtil;
import com.dongdongshop.vo.Cart;
import com.dongdongshop.vo.OrderPayment;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
@DubboService
public class OrderServiceImpl implements OrderService {
    @Resource
    private TbOrderMapper     tbOrderMapper;
    @Resource
    private TbOrderItemMapper tbOrderItemMapper;
    @Override
    @Transactional
    public OrderPayment addOrder(TbOrder order,TbUser user) {
        /*更具用户id在数据库中查询用户的购物车*/
        List<Cart> cartList = selectCartListRedis(user.getId());
        IdWorker worker = new IdWorker();
        /*支付订单号*/
        String orderNum = String.valueOf(worker.nextId());
        /*付款总金额*/
        Double paymentAmount = 0.0;
        /*先遍历商家*/
        for (Cart cart : cartList) {
            /*使用工具类生成订单ID*/
            long orderId = worker.nextId();
            /*生成订单表对象*/
            TbOrder tbOrder = new TbOrder();
            tbOrder.setOrderId(orderId);//订单id
            tbOrder.setUserId(user.getUsername());//用户名称
            tbOrder.setPaymentType(order.getPaymentType());//支付类型
            tbOrder.setStatus("1");//支付状态,默认待支付
            tbOrder.setCreateTime(new Date());/*订单创建时间*/
            tbOrder.setUpdateTime(new Date());/*订单更新时间*/
            tbOrder.setReceiverAreaName(order.getReceiverAreaName());/*地址*/
            tbOrder.setReceiverMobile(order.getReceiverMobile());//手机号
            tbOrder.setReceiver(order.getReceiver());//收货人
            tbOrder.setSourceType("2");//订单来源：1:app端，2：pc端，3：M端，4：微信端，5：手机qq端',
            tbOrder.setSellerId(cart.getSellerId());/*商家Id*/
            tbOrder.setOrderNum(orderNum);/*支付订单号*/
            /*在遍历每个购买的每个商家的商品*/
            List<TbOrderItem> orderItemList = cart.getOrderItemList();
            double  total = 0.0;//用于接收总金额
            for (TbOrderItem orderItem : orderItemList) {
                long orderItemId = worker.nextId();
                orderItem.setId(orderItemId);//订单id
                orderItem.setSellerId(cart.getSellerId());//商家id
                orderItem.setOrderId(orderId);//商家id
                orderItem.setOrderNum(orderNum);//交易订单号
                /*将每个商家的商品价格累加*/
                total += orderItem.getTotalFee().doubleValue();
                tbOrderItemMapper.insert(orderItem);//添加商品售卖表
            }
            tbOrder.setPayment(new BigDecimal(total));
            tbOrderMapper.insert(tbOrder);//添加商品详情表
            paymentAmount += total;
        }
        RedisTemplate redis = RedisUtil.redis;
        /*删除redis中的数据*/
        if (redis.delete(RedisConstant.COOKIE_CARTLIST)){
            /*
            * * @param WIDout_trade_no 商户订单号，商户网站订单系统中唯一订单号，必填
             * @param WIDtotal_amount 付款金额，必填
             * @param WIDsubject 订单名称，必填
             * @param WIDbody 商品描述，可空
            * */

            OrderPayment orderPayment = new OrderPayment();
            orderPayment.setWIDout_trade_no(orderNum);
            orderPayment.setWIDtotal_amount(String.valueOf(paymentAmount));
            orderPayment.setWIDsubject("东东商城");
            orderPayment.setWIDbody("不知道");
            return orderPayment;
        }else {
            return null;
        }

    }

    public List<Cart> selectCartListRedis(Long id) {
        RedisTemplate redis = RedisUtil.redis;
        /*从redis中获取用户收藏的的商家和商品*/
        List<Cart> cartList = (List<Cart>)redis.boundHashOps(RedisConstant.COOKIE_CARTLIST).get(id);
        return cartList == null ? new ArrayList<>() : cartList;
    }

    /**
     *更具交易订单号添加交易流水号
     * @param out_trade_no 商户交易订单号
     * @param trade_no 支付宝交易号
     */
    @Override
    @Transactional
    public void insertTradeNo(String out_trade_no, String trade_no) {
        tbOrderMapper.updateOutTradeNoByTradeNo(out_trade_no,trade_no);
        tbOrderItemMapper.updateOutTradeNoByTradeNo(out_trade_no,trade_no);
    }

    @Override
    public List<TbOrder>  selectByOrderNum(String orderNum, String tradeNo) {
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andOrderNumEqualTo(orderNum);
        if (tradeNo != null){
            criteria.andTradeNoEqualTo(tradeNo);
        }
        List<TbOrder> tbOrders = tbOrderMapper.selectByExample(example);
        return tbOrders;
    }

    @Override
    public List<TbOrder> selectByUserName(String name) {
        TbOrderExample example = new TbOrderExample();
        example.setOrderByClause("update_time DESC");
        TbOrderExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(name);
        criteria.andStatusNotEqualTo("1");
        criteria.andStatusNotEqualTo("7");
        List<TbOrder> orderList = tbOrderMapper.selectByExample(example);
        return orderList.size() == 0 ? null : orderList;
    }

    @Override
    public void orderRefundByTradeNo(String orderNum) {
        /*更具订单号修改状态*/
        tbOrderMapper.updateStatusByOrderNum(orderNum);
    }
    @Override
    public Integer selectByYesterday() {
        //        查询今日订单
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        String today= DateUtil.today();
        Date date1 = DateUtil.parse(today + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        criteria.andPaymentTimeGreaterThan(date1);//大于
        Date date2 = DateUtil.parse(today + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
        criteria.andPaymentTimeLessThan(date2);//小于
        List<TbOrder> orderList = tbOrderMapper.selectByExample(example);
        return orderList.size();
    }

    @Override
    public Integer selectByToday() {
        //昨日订单数
        String yesterday = DateUtil.yesterday().toString("yyyy-MM-dd");
        TbOrderExample example = new TbOrderExample();
        TbOrderExample.Criteria criteria = example.createCriteria();
        Date date1 = DateUtil.parse(yesterday + " 00:00:00", "yyyy-MM-dd HH:mm:ss");
        criteria.andPaymentTimeGreaterThan(date1);//大于
        Date date2 = DateUtil.parse(yesterday + " 23:59:59", "yyyy-MM-dd HH:mm:ss");
        criteria.andPaymentTimeLessThan(date2);//小于
        List<TbOrder> orderList = tbOrderMapper.selectByExample(example);
        return orderList.size();
    }
}
